<template>
  <div>
    <Head />

    <!-- menubar start-->
    <div class="menubar-area">
      <div class="container">
        <div class="row">
          <div class="mainMenu">
            <ul>
              <li>
                <el-dropdown v-if="userName" placement="bottom">
                  <span class="el-dropdown-link">
                    <router-link to="/userLogin">{{ userName }}<i class="el-icon-arrow-down el-icon--right" style="font-size: 16px; padding: 0 0 0 5px;" /></router-link>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-if="!$store.getters.roles.includes('user')" @click.native="toManage()">管理界面</el-dropdown-item>
                    <el-dropdown-item @click.native="modifyPassword()">修改密码</el-dropdown-item>
                    <el-dropdown-item @click.native="logOut()">登出</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <router-link
                  v-else
                  :to="{path: '/userLogin', name: 'userLogin'}"
                  title="登录"
                ><i class="el-icon-user" style="font-size: 20px" />
                </router-link>
              </li>
              <li>
                <el-dropdown :hide-on-click="true">
                  <span class="el-dropdown-link">
                    书籍分类<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown" :placement="'bottom-start'" node-key="id">
                    <el-dropdown-item>
                      <el-tree ref="tree" :data="categorys" accordion :props="defaultProps" node-key="id" @node-click="handleNodeClick" />
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </li>
              <li>
                <router-link
                  v-if="userId"
                  :to="{path: '/shoppingCart', name: 'shoppingCart'}"
                ><i class="el-icon-shopping-cart-2" style="font-size: 20px;" /> 我的购物车</router-link>
              </li>
              <li>
                <router-link
                  v-if="userId"
                  :to="{path: '/ordersManage', name: 'ordersManage'}"
                ><i class="el-icon-sell" style="font-size: 20px;" /> 我的订单</router-link>
              </li>
            </ul>
          </div>
          <div class="otherMenu" style="font-size: 24px">
            <div class="search">
              <el-input id="searchInput" v-model="input" maxlength="20" placeholder="请输入书籍名称" @keyup.enter.exact.native="search(input, 1, $event)" />
              <i class="el-icon-search" @click="search(input, 1)" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- menubar end-->

    <!-- post start-->
    <div class="post-area">
      <div class="container">
        <div class="section">
          <span>热销图书</span>
        </div>
        <div class="row">
          <div class="leftPost">
            <!--
            rankingBooks[x]是vuex中state管理加载的数据，异步调用显示，然后vue渲染机制中：
            异步数据先显示初始数据，再显示带数据的数据，
            所以上来加载rankingBooks[x]时候还是一个空对象
            所以这里用v-if判断是否加载，不能用v-show,v-show是先完成加载再判断
            -->
            <div v-if="rankingBooks[2]" class="three flowing">
              <div class="thumb">
                <router-link :to="{path: '/bookDetails?id=' + rankingBooks[2].id}">
                  <img :src="rankingBooks[2].cover" alt="image">
                </router-link>
              </div>
              <div class="details">
                <el-link class="NOtag" :underline="false" title="销量排名">No.3</el-link>
                <el-link class="CALtag" :underline="false" title="分类">{{ rankingBooks[2].secondcategory }}</el-link>
                <h6><router-link :to="{path: '/bookDetails?id=' + rankingBooks[2].id}">{{ rankingBooks[2].bookName }}</router-link></h6>
                <div class="meta">
                  <i class="el-icon-price-tag" title="价格" /> ￥{{ rankingBooks[2].price }}
                  <i class="el-icon-user-solid" title="作者" /> {{ rankingBooks[2].author }}
                </div>
              </div>
            </div>
            <div v-if="rankingBooks[1]" class="two flowing">
              <div class="thumb">
                <router-link :to="{path: '/bookDetails?id=' + rankingBooks[1].id}">
                  <img :src="rankingBooks[1].cover" alt="image">
                </router-link>
              </div>
              <div class="details">
                <el-link class="NOtag" :underline="false" title="销量排名">No.2</el-link>
                <el-link class="CALtag" :underline="false" title="分类">{{ rankingBooks[1].secondcategory }}</el-link>
                <h6><router-link :to="{path: '/bookDetails?id=' + rankingBooks[1].id}">{{ rankingBooks[1].bookName }}</router-link></h6>
                <div class="meta">
                  <i class="el-icon-price-tag" title="价格" /> ￥{{ rankingBooks[1].price }}
                  <i class="el-icon-user-solid" title="作者" /> {{ rankingBooks[1].author }}
                </div>
              </div>
            </div>
          </div>
          <div v-if="rankingBooks[0]" class="rightPost one flowing">
            <div class="thumb">
              <router-link :to="{path: '/bookDetails?id=' + rankingBooks[0].id}">
                <img :src="rankingBooks[0].cover" alt="image">
              </router-link>
            </div>
            <div class="details">
              <el-link class="NOtag" :underline="false" title="销量排名">No.1</el-link>
              <el-link class="CALtag" :underline="false" title="分类">{{ rankingBooks[0].secondcategory }}</el-link>
              <h6><router-link :to="{path: '/bookDetails?id=' + rankingBooks[0].id}">{{ rankingBooks[0].bookName }}</router-link></h6>
              <div class="meta">
                <i class="el-icon-price-tag" title="价格" /> ￥{{ rankingBooks[0].price }}
                <i class="el-icon-user-solid" title="作者" /> {{ rankingBooks[0].author }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- post end-->

    <!-- books start-->
    <div class="books-area">
      <div class="container">
        <div ref="exhibition" class="section">
          <span>精选图书<i style="font-size: 28px;" class="el-icon-refresh" title="重置" @click="reload()" /></span>
        </div>
        <div class="row">
          <div v-for="post in posts" :key="post.id" class="bookitem hovering">
            <div class="thumb">
              <router-link :to="{path: '/bookDetails', name: 'bookDetails', query: { id: post.id } }">
                <img :src="post.cover" alt="image">
              </router-link>
            </div>
            <div class="details">
              <el-link class="CALtag" :underline="false" title="出版社">{{ post.press }}</el-link>
              <h6><router-link :to="{path: '/bookDetails', name: 'bookDetails', query: { id: post.id } }">{{ post.bookName }}</router-link></h6>
              <div class="meta">
                <i class="el-icon-price-tag" title="价格" /> ￥{{ post.price }}
                <i class="el-icon-user-solid" title="作者" /> {{ post.author }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- books end-->

    <!-- pagination start-->
    <div class="pagination-area">
      <div class="container">
        <div class="row">
          <el-pagination
            background
            layout="prev, pager, next"
            :page-size="pageSize"
            :total="allbookNum"
            @current-change="page"
          />
        </div>
      </div>
    </div>
    <!-- pagination end-->

    <Foot />
  </div>
</template>

<script>
import userApi from '@/api/user'
import Head from '@/views/user/component/Head'
import Foot from '@/views/user/component/Footer'

export default {
  components: { Head, Foot },
  inject: ['reload'],
  data() {
    return {
      posts: [],
      input: '',
      pageSize: 12,
      user: false,
      userId: 0,
      userName: 0,
      currentPage: 0,
      allbookNum: 0,
      rankingIds: {},
      rankingBooks: [],
      categorys: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 用于存储分类查询id
      parentID: 0,
      childID: 0
    }
  },
  // computed() {
  //   (role) => { return this.$store.getters.role }
  // },
  created: async function() {
    // 接收user相关参数
    this.userName = 0
    this.userId = this.$store.getters.token
    if (this.userId) this.userName = this.$store.getters.name
    this.initData()
  },
  methods: {
    reloadIndex() {
      this.reload()
    },
    async initData() {
      // 获取销量排名前三的书籍
      await userApi.ranking().then(resp => {
        this.rankingIds = Object.entries(resp.data.data.rank)
        this.rankingIds.sort((a, b) => { return b[1] - a[1] })
      }, err => {
        console.log(err)
      })
      // 循环中的异步操作需要async + await确保输出顺序
      // 并且这里不适合使用forEach遍历,forEach内部封装了while（async + await不起作用）
      for (let i = 0; i < this.rankingIds.length; i++) {
        await userApi.getBookById(this.rankingIds[i][0]).then(resp => {
          var id = this.rankingIds[i][0]
          this.rankingBooks.push(resp.data.data[id])
        },
        err => {
          console.log(err)
        })
      }

      // 获取各类信息
      userApi.getPage(1).then(resp => {
        this.posts = resp.data.data.books
      }, err => {
        console.log(err)
      })
      userApi.getAllCategory().then(resp => {
        // 获取分类树的信息
        var allCal = resp.data.data.data
        allCal.forEach(cal => {
          const childrenInfo = []
          cal.children.forEach(child => {
            childrenInfo.push({ label: child.title, id: child.id, level: child.level })
          })
          this.categorys.push({ label: cal.title, id: cal.id, level: cal.level, children: childrenInfo })
        })
      }, err => {
        console.log(err)
      })
      await userApi.getAllbooks().then(resp => {
        this.allbookNum = resp.data.data.books.length
      }, err => {
        console.log(err)
      })
    },
    // 登出，即删除cookie中的token
    async logOut() {
      this.$store.dispatch('user/logout').then(() => {
        this.userName = 0
        this.userId = 0
        this.$message.success('已注销!')
      }).catch(err => {
        this.$message.error(err.message) // 登录失败提示错误
      })
    },
    // 点击获取当前分页下的图书
    page(currentPage) {
      if (!this.input) {
        userApi.getPage(currentPage).then(resp => {
          this.posts = resp.data.data.books
        }, err => {
          console.log(err)
        })
      } else {
        this.search(this.input, currentPage)
      }
    },
    search(input, currentPage, event) {
      userApi.selectByCondition(input, currentPage).then(resp => {
        // 获取数据
        this.posts = resp.data.data.books.records
        this.pageSize = resp.data.data.books.size
        this.allbookNum = resp.data.data.books.total
        // 滚动至展示部分并使输入框失焦
        this.$refs.exhibition.scrollIntoView()
        event && event.target.blur()
      }, err => {
        console.log(err)
      })
    },
    seachByCategory(subId, parentId) {
      userApi.getbookbyCategory(parentId, subId).then(resp => {
        // 调整分页按钮对应参数
        this.posts = resp.data.data.books
        this.pageSize = Object.keys(resp.data.data.books).length
        this.allbookNum = Object.keys(resp.data.data.books).length
        // 滚动至展示部分
        this.$refs.exhibition.scrollIntoView()
      }, err => {
        console.log(err)
      })
    },
    handleNodeClick(data) {
      !data.level ? this.parentID = data.id : this.childID = data.id
      this.childID && this.seachByCategory(this.childID, this.parentID)
      this.childID = 0
    },
    modifyPassword() {
      this.$router.push({ path: '/modifyPassword' })
    },
    toManage() {
      this.$router.push({ path: '/panelChild' })
    }
  }
}
</script>

<style scoped>
.container {
    width: 100%;
    max-width: 1140px;
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}
.row {
  display: flex;
  justify-content: space-between;
}
.menubar-area .mainMenu {
  position: relative;
  flex: 2;
  min-height: 60px;
  width: 100%;
}
.menubar-area .mainMenu ul {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  justify-content: space-between;
}
.menubar-area .mainMenu ul li {
  padding: 0 30px 0 20px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 16px;
}
.menubar-area .mainMenu .el-dropdown {
  font-family: 'Courier New', Courier, monospace;
  font-size: 16px;
  cursor: pointer;
}
.el-dropdown-menu__item:not(.is-disabled):hover,
.el-dropdown-menu__item:focus {
  background-color: #fff!important;
}
.menubar-area {
  margin-bottom: 30px;
}
.menubar-area .otherMenu {
  position: relative;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex: 1;
  width: 100%;
  min-height: 60px;
  line-height: 60px;
  max-width: 66.666666%;
}
.menubar-area .otherMenu i {
  cursor: pointer;
  padding: 0 10px 0 20px;
  font-size: 24px;
}
.menubar-area .otherMenu i:hover {
  color: #337AB7;
  transition: .3s;
}
.menubar-area .otherMenu .search {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding-left: 50px;
}
.menubar-area .otherMenu >>> .el-input__inner {
  width: 100%;
  border: none;
  border-radius: 0;
  border-bottom: 1px solid #DCDFE6;
}
.menubar-area .otherMenu >>> .el-input__inner:focus {
  border-color: #409EFF;
  outline: 0;
}
.menubar-area .otherMenu >>> .el-dropdown {
  font-family: 'Courier New', Courier, monospace;
  font-size: 16px;
}
.post-area {
  padding-bottom: 40px;
}
.post-area .row {
  justify-content: space-between;
}
.post-area .bookitem {
  height: 310px;
  width: 255px;
  max-height: 310px;
  max-width: 255px;
  margin-right: 10px;
}
.post-area .leftPost .two ,
.post-area .leftPost .three {
  position: relative;
  min-width: 350px;
  min-height: 310px;
}
.post-area .leftPost .three {
  margin-bottom: 30px;
}
.post-area .leftPost img,
.post-area .rightPost img {
  border-radius: 10px;
}
.post-area .leftPost img {
  width: 350px;
  height: 310px;
  min-width: 350px;
  min-height: 310px;
}
.post-area .rightPost {
  position: relative;
  max-width: 730px;
  max-height: 650px;
  display: flex;
  flex: 3;
  flex-direction: column;
  justify-content: flex-start;
}
.post-area .rightPost img {
  height: 100%;
  height: 650px;
  width: 730px;
  max-width: 730px;
  max-height: 650px;
}
.post-area .details {
  position: absolute;
  bottom: 30px;
  left: 30px;
}
.post-area .details .NOtag,
.post-area .details .CALtag {
  display: inline-block;
  height: 30px;
  padding: 0 11px;
  margin-right: 10px;
  cursor: default;
  border-radius: 3px;
  line-height: 30px;
  font-weight: 300;
  font-size: 14px;
  color: #ffffff;
  background: linear-gradient(to left,#55dde0, #ffc2d4);
}
.post-area .details .CALtag {
  background: linear-gradient(to left,#83e377, #ffd60a);
}
.post-area h6 a {
  display: inline-block;
  line-height: 26px;
  margin-top: 12px;
  font-weight: 600;
  font-size: 24px;
  margin-bottom: 0;
  color: #fff;
}
.post-area h6:hover a {
  color: #147df5;
  transition: all .6s;
}
.post-area .meta {
  margin-top: 16px;
  font-size: 16px;
  font-weight: 800;
  color: #fff8f0;
}
.post-area .meta i {
  font-size: 16px;
  color: #218380;
}
.post-area .meta i:nth-child(2) {
  margin-left: 20px;
}
.books-area {
  padding-bottom: 30px;
}
.books-area .section,
.post-area .section {
  width: 100%;
  background: #52b69a;
  border-radius: 5px;
  padding: 14px 20px;
  margin-bottom: 40px;
}
.books-area .section span,
.post-area .section span {
  font-family: 'Courier New', Courier, monospace;
  font-size: 20px;
  font-weight: 800;
  color: #ffffff;
}
.books-area .section span {
  display: flex;
  justify-content: space-between;
  cursor: pointer;
}
.books-area .row {
  flex-wrap: wrap;
  justify-content: space-between;
  align-content: space-between;
}
.books-area .bookitem {
  position: relative;
  height: 240px;
  width: 255px;
  margin-bottom: 30px;
  max-height: 240px;
  max-width: 255px;
  transition: transform .5s;
}
/* 如果最后一行是3个元素 */
.books-area .row .bookitem:last-child:nth-child(4n - 1) {
    margin-right: calc(24% + 5% / 3);
}
/* 如果最后一行是2个元素 */
.books-area .row .bookitem:last-child:nth-child(4n - 2) {
    margin-right: calc(48% + 10% / 3);
}
.books-area .bookitem img {
  height: 240px;
  width: 255px;
  max-height: 310px;
  max-width: 255px;
  border-radius: 10px;
}
.books-area .details {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-60%);
}
.books-area .details .CALtag {
  height: 24px;
  display: inline-block;
  padding: 0 11px;
  margin-right: 10px;
  cursor: default;
  line-height: 24px;
  font-size: 14px;
  color: #ffffff;
  font-weight: 300;
  border-radius: 3px;
  background: linear-gradient(to left,#fe8c46, #2ec4b6);
}
.books-area h6 a {
  display: inline-block;
  margin-top: 12px;
  line-height: 16px;
  font-weight: 600;
  font-size: 16px;
  margin-bottom: 0;
  color: #fff;
}
.books-area h6 a:hover {
  color: #06d6a0;
  transition: .4s;
}
.books-area .meta {
  margin-top: 10px;
  white-space:nowrap;
  font-size: 16px;
  font-weight: 800;
  color: #ff8811;
}
.books-area .meta i {
  font-size: 14px;
  color: #218380;
}
.books-area .meta i:nth-child(2) {
  margin-left: 10px;
}
.pagination-area {
  margin-bottom: 30px;
}
.pagination-area .row {
  justify-content: center;
}

/* 悬停效果 */
.hovering::after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 10px;
    transition: opacity 2s cubic-bezier(0.165, 0.84, 0.44, 1);
    box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.15);
    content: '';
    opacity: 0;
    z-index: -1;
}
.hovering:hover,
.hovering:focus {
    transform: scale3d(1.006, 1.006, 1);
}
.hovering:hover::after,
.hovering:focus::after {
    opacity: 1;
}
.flowing::before,
.flowing::after {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    border-radius: 10px;
    transition: opacity .38s ease-in-out, transform .35s ease-in-out;
    content: '';
    opacity: 0;
    pointer-events: none;
}
.flowing::before {
    transform: scale3d(0, 1, 1);
    transform-origin: left top;
    border-top: 2px solid #5465ff;
    border-bottom: 2.5px solid #ff5d8f;
}
.flowing::after {
    transform: scale3d(1, 0, 1);
    transform-origin: right top;
    border-right: 2.5px solid #ff5d8f;
    border-left: 2px solid #5465ff;
}
.flowing:hover::before,
.flowing:hover::after,
.flowing:focus::before,
.flowing:focus::after {
    transform: scale3d(1, 1, 1);
    opacity: 1;
}
</style>
